package com.ysm.smfu.welcome;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.ysm.smfu.MainActivity;
import com.ysm.smfu.R;
import com.ysm.smfu.activity.BaseActivity;
import com.ysm.smfu.bean.AdBean;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.MyImageBitmapUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.StoreInfo;
import com.ysm.smfu.utils.UIUtils;

//软件入口，闪屏界面
public class FlashActivity extends BaseActivity {
    private boolean first;    //判断是否第一次打开软件
    private static int TIME = 500; // 进入主程序的延迟时间
    //    屏幕密度
    private int densityDpi;
    //    是否显示广告页
    private boolean isShowAdPage = true;
    private SharedConfig sharedConfig;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.flash_page);
        // 得到配置文件
        getConfig();
        //解决点击home键返回，再点击图标重启应用
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        getAdInfo();
        getAdList();
//        友盟SDK会对日志进行加密
        MobclickAgent.enableEncrypt(true);
    }

    boolean isGetAdList;

    /**
     * 获取活动信息
     */
    private void getAdList() {
        BaseProtocal.builder(false).getAdListData(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("首页活动信息", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    isGetAdList = true;
                    sharedConfig.saveCommoneStringInfo(SpKey.ADLISTDATA, response);
                }
            }

            @Override
            public void onFail(Exception e) {
            }
        });
    }

    private void getConfig() {
        sharedConfig = new SharedConfig(UIUtils.getContext());
        first = sharedConfig.getCommoneBooleanInfo("first");
        StoreInfo.getInstance().clear(sharedConfig.getCommoneSp());
//        获取屏幕密度
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        densityDpi = metric.densityDpi;
    }

    /**
     * 获取广告数据
     */
    private void getAdInfo() {
        BaseProtocal.builder(false)
                .getAdData(new MyStringCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        PrintUtil.printRespones("广告页数据", response);
                        String state = JsonUtil.getState(response);
                        if (TextUtils.equals(state, "1")) {
                            isShowAdPage = true;
                            AdBean adBean = new Gson().fromJson(response, AdBean.class);
                            saveAdInfo(adBean);
                        } else {
                            isShowAdPage = false;
                            clearAdData();
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
//                        没有网络从本地获取上一个
                        isShowAdPage = true;
                    }
                }, this);
    }

    /**
     * 清空本地广告数据
     */
    private void clearAdData() {
        sharedConfig.saveCommoneStringInfo(SpKey.PREADID, "");
        sharedConfig.saveCommoneStringInfo(SpKey.PREADIMG, "");
        sharedConfig.saveCommoneStringInfo(SpKey.PREADLINK, "");
        MyImageBitmapUtil.saveBitmapLoc(null, SpKey.LOCALADIMGADD);
    }

    /**
     * 保存广告信息
     */
    private void saveAdInfo(AdBean adBean) {
        String imgAdd;
        String linkAdd = adBean.activityURL;
        if (densityDpi >= 320)
            imgAdd = adBean.andImg1;
        else if (densityDpi >= 240)
            imgAdd = adBean.andImg2;
        else
            imgAdd = adBean.andImg3;

        if (first) {//如果是第一次进入，保存到上一次获取到的广告信息里，第一次不展示广告，只是保存信息
            sharedConfig.saveCommoneStringInfo(SpKey.PREADIMG, imgAdd);
            sharedConfig.saveCommoneStringInfo(SpKey.PREADLINK, linkAdd);
            sharedConfig.saveCommoneStringInfo(SpKey.PREADID, adBean.activityId);
        } else {
            sharedConfig.saveCommoneStringInfo(SpKey.CURRADIMG, imgAdd);
            sharedConfig.saveCommoneStringInfo(SpKey.CURRLINK, linkAdd);
            sharedConfig.saveCommoneStringInfo(SpKey.CURRPREADID, adBean.activityId);
        }
    }

    @Override
    protected void afterResume() {
        super.afterResume();
        handler.sendEmptyMessageDelayed(100, TIME);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            goHome();
        }
    };

    // 进入主程序的方法
    private void goHome() {
//        //如果第一次，则进入引导页WelcomeActivity
//        if (first) {
//            goWeclomePage();
//        }
        goMainPage();
    }

    /**
     * 跳往欢迎页
     */
    private void goWeclomePage() {
        goActivityLTR(WelcomeActivity.class);
    }

    /**
     * 跳往主页
     */
    private void goMainPage() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("isShowAdPage", isShowAdPage);
        startActivity(intent);
        finish();
    }

    /**
     * 从左到右切换
     *
     * @param clazz
     */
    public void goActivityLTR(Class clazz) {
        UIUtils.startActivity(clazz);
//        overridePendingTransition(R.anim.in_from_right,
//                R.anim.out_to_left);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        移除handler消息
        handler.removeMessages(100);
//        取消广告请求
        BaseProtocal.cancleAdData();
        BaseProtocal.cancleAdListData();
        if (!isGetAdList)
            sharedConfig.saveCommoneStringInfo(SpKey.ADLISTDATA, "");
    }
}

